<template>
  <div class="app-container">
    <el-form
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      label-width="68px"
      class="query-form"
      size="small"
    >
      <el-form-item label="策略名称" prop="strategyName">
        <el-input
          v-model="queryParams.strategyName"
          placeholder="请输入策略名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="content-container height_100-query_from">
      <div class="handle_bar">
        <div class="tit"><span>批量控制</span></div>
        <el-button
          v-hasPermi="['fen:multipleControl:add']"
          type="primary"
          plain
          size="small"
          @click="handleAdd"
        >新增</el-button>
      </div>
      <div class="flex-1" style="position: relative;overflow: hidden;">
        <div style="position: absolute;left: 0;top: 0;bottom: 0;right: 0;display: flex;flex-direction: column;overflow: hidden;z-index:0;">
          <el-table
            v-loading="loading"
            class="flex-1"
            height="250"
            style="width:100%;"
            :data="controlList"
            @selection-change="handleSelectionChange"
            @expand-change="expandChange"
          >
            <el-table-column type="expand" label="查看">
              <template slot-scope="props">
                <el-table
                  v-loading="expandLoading"
                  :data="props.row.detailList"
                  style="width:540px;"
                  :border="true"
                >
                  <el-table-column prop="equName" label="风机名称" width="180" />
                  <el-table-column prop="locationName" label="风机位置" width="180" />
                  <el-table-column prop="frequency" label="风机频率" width="180" />
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="策略名称" align="center" prop="strategyName" />
            <el-table-column label="描述" align="center" prop="remark" />
            <el-table-column label="控制台数" align="center" prop="controlNum" />
            <el-table-column label="运行方式" align="center" prop="runningStatus">
              <template slot-scope="scope">
                <span v-if="scope.row.runningStatus == 1">常开</span>
                <span v-if="scope.row.runningStatus == 2">自定义</span>
                <span v-if="scope.row.runningStatus == 3">每天（自定义时间段）</span>
              </template>
            </el-table-column>
            <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
            <el-table-column label="结束时间" align="center" prop="endTime" width="180" />
            <el-table-column label="创建人员" align="center" prop="createUser" />
            <el-table-column label="执行人员" align="center" prop="executeUser" />
            <el-table-column label="执行时间" align="center" prop="executeTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.executeTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="执行状态" align="center" prop="status" fixed="right">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  :disabled="!checkPermi(['fen:multipleControl:run'])"
                  active-color="#13ce66"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeRunStatus"
                />
                <!-- <span v-if="scope.row.status == 1" class="text-info">执行</span>
                <span v-if="scope.row.status == 0">未执行</span> -->
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" width="120">
              <template slot-scope="scope">
                <el-button
                  v-hasPermi="['fen:multipleControl:edit']"
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                >修改</el-button>
                <el-button
                  v-hasPermi="['fen:multipleControl:del']"
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改批量控制对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="620px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left">
        <el-form-item label="策略名称" prop="strategyName">
          <el-input v-model="form.strategyName" placeholder="请输入策略名称" />
        </el-form-item>
        <el-form-item label="策略介绍" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入描述" type="textarea" />
        </el-form-item>
        <el-form-item label="开启时间" prop="runningStatus">
          <el-form-item label-width="0" style="margin-bottom: 0;">
            <el-radio-group v-model="form.runningStatus">
              <el-radio :label="1">常开</el-radio>
              <el-radio :label="2">自定义</el-radio>
              <el-radio :label="3">每天（自定义时间段）</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="form.runningStatus == 2 || form.runningStatus == 3" style="display:flex;">
            <el-form-item prop="startTime" label-width="0" style="width:calc(100% - 16px)">
              <el-time-picker
                v-model="form.startTime"
                clearable
                size="small"
                value-format="hh:mm:ss"
                placeholder="选择开始时间"
                style="width:100%;"
              />
            </el-form-item>
            <div style="width:30px;text-align: center;">～</div>
            <el-form-item prop="endTime" label-width="0" style="width:calc(100% - 16px)">
              <el-time-picker
                v-model="form.endTime"
                clearable
                size="small"
                value-format="hh:mm:ss"
                placeholder="选择结束时间"
                style="width:100%;"
              />
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="风机控制" style="margin-bottom: 0;" />
        <el-table
          :data="form.detailList"
          style="width: 100%"
          size="small"
        >
          <el-table-column prop="equName" label="风机名称" width="180" />
          <el-table-column prop="locationName" label="风机位置" width="180" />
          <el-table-column prop="frequency" label="风机频率" width="180" fixed="right">
            <template slot-scope="{row,$index}">
              <el-form-item
                :prop="'detailList.' + $index + '.frequency'"
                :rules="[
                  { required: true, message: '请输入风机频率', trigger: 'blur'},
                  { validator: validateFrequency, trigger: 'blur' }
                ]"
                style="margin-bottom: 0;"
                label-width="0"
              >
                <el-input v-model="row.frequency" placeholder="风机频率" type="number" :min="0" :max="50">
                  <template slot="append">Hz</template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleDelEqu(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" style="width:100%;border-radius: 0;" size="small" @click="openAddEqu">添加设备</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <AddMultipleEqu ref="AddMultipleEqu" @success="handleAddEqu" />
  </div>
</template>

<script>
import AddMultipleEqu from './components/AddMultipleEqu.vue'
import { listControl, getControl, delControl, addControl, updateControl, switchRunStatus } from '@/api/fjgs/fjMutipleControl'
import { checkPermi } from '@/utils/permission'
export default {
  name: 'Control',
  components: {
    AddMultipleEqu
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      expandLoading: false,
      deviceList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 批量控制表格数据
      controlList: [
      ],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        strategyName: null,
        controlNum: null,
        runningStatus: null,
        startTime: null,
        endTime: null,
        status: null,
        createUser: null,
        executeUser: null,
        executeTime: null
      },
      // 表单参数
      form: {
        detailList: []
      },
      // 表单校验
      rules: {
        strategyName: [{ required: true, message: '请输入策略名称', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入策略介绍', trigger: 'blur' }],
        runningStatus: [{ required: true, message: '请选择开启方式', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择时间', trigger: 'blur' }],
        endTime: [{ required: true, message: '请选择时间', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermi: checkPermi,
    expandChange(row) {
      // this.expandLoading = true
      this.detailList = []
      getControl(row.id).then(response => {
        row.detailList = response.data.detailList
        // this.expandLoading = false

        // this.form = response.data
        // this.open = true
        // this.title = '修改批量控制'
      })
    },
    changeRunStatus(row) {
      const status = row.status
      switchRunStatus(row.id).then(res => {
        if (res.code == 200) {
          this.getList()
          this.msgSuccess('操作成功')
        } else {
          row.status = status
        }
      }).catch(() => {
        this.msgError('操作失败')
      })
    },
    openAddEqu() {
      this.$refs.AddMultipleEqu.open(this.form.detailList)
    },
    handleAddEqu(equs) {
      // console.log(Array.isArray(this.form.detailList) && Array.isArray(equs), equs)
      if (Array.isArray(this.form.detailList) && Array.isArray(equs)) {
        this.form.detailList = [...this.form.detailList, ...equs]
      } else {
        this.$set(this.form, 'detailList', equs || [])
        // this.form.detailList = equs || []
      }
    },
    handleDelEqu(row) {
      const index = this.form.detailList.indexOf(row)
      this.form.detailList.splice(index, 1)
    },
    validateFrequency(rule, value, callback) {
      if (value === '') {
        callback('请输入风机频率')
      } else if (value > 50 || value < 0) {
        this.msgError('风机频率范围0~50')
        callback(new Error('风机频率0~50'))
      } else {
        callback()
      }
    },
    /** 查询批量控制列表 */
    getList() {
      this.loading = true
      listControl(this.queryParams).then(response => {
        this.controlList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        strategyName: null,
        remark: null,
        controlNum: null,
        runningStatus: 0,
        startTime: null,
        endTime: null,
        status: 0,
        createUser: null,
        createTime: null,
        executeUser: null,
        executeTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加批量控制'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getControl(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改批量控制'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateControl(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addControl(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除批量控制编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delControl(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fj/control/export', {
        ...this.queryParams
      }, `fj_control.xlsx`)
    }
  }
}
</script>
<style>
.demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
